package activity

import (
	"context"
	"fmt"
	"strconv"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/common/moneyx"
	enum "mall/service/backend/common/enum/promotion"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/promotion/model"
	"mall/service/promotion/rpc/internal/svc"
	"mall/service/promotion/rpc/internal/utils/errorhandler"
	"mall/service/promotion/rpc/types/promotion"

	"github.com/sirupsen/logrus"
	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type BackendUpdateActivityLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendUpdateActivityLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendUpdateActivityLogic {
	return &BackendUpdateActivityLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendUpdateActivityLogic) BackendUpdateActivity(in *promotion.ActivityInfo) (*promotion.BaseResp, error) {
	logx.Infof("BackendUpdateActivity : %+v ", in)
	// logrus.Info(fmt.Sprintf("BackendUpdateActivity: %+v", in))

	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if len(in.Ids) > 0 { // 批量修改状态
		now := time.Now()
		for _, id := range in.Ids {
			if id > 0 && in.Status != nil {
				activity, err := l.svcCtx.Activity.FindOneNoCache(l.ctx, tx, id)
				if err != nil {
					tx.Rollback()
					return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
				}

				activity.Status = uint16(*in.Status)
				activity.UpdatedAt = now
				err = l.svcCtx.Activity.Update(l.ctx, tx, activity, nil)
				if err != nil {
					tx.Rollback()
					return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
				}
			}
		}

		tx.Commit()

		return &promotion.BaseResp{
			Msg: i18n.UpdateSuccess,
		}, nil
	}

	if in.Id == nil || *in.Id == 0 {
		// logrus.Info(fmt.Sprintf("BackendUpdateActivity id error: %+v", in))
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	if in.Name != nil && len(strings.TrimSpace(*in.Name)) == 0 {
		return nil, errorx.NewInvalidArgumentError("promotion.activityNameRequired")
	}

	id := *in.Id

	data, err := l.svcCtx.Activity.FindOneNoCache(l.ctx, nil, id)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	var skipMeta bool
	if in.SkipMeta != nil && *in.SkipMeta > 0 {
		skipMeta = true
	}
	var skipMedia bool
	if in.SkipMedia != nil && *in.SkipMedia > 0 {
		skipMedia = true
	}
	var skipContent bool
	if in.SkipContent != nil && *in.SkipContent > 0 {
		skipContent = true
	}

	if data.Status != uint16(globalkey.StatusPending) &&
		data.Status != uint16(globalkey.StatusApproved) &&
		data.Status != uint16(globalkey.StatusRejected) {
		return nil, errorx.NewInvalidArgumentError("promotion.activityStatusInvalid")
	}

	if in.ActivityType != nil && data.ActivityType != uint8(*in.ActivityType) {
		// logrus.Info(fmt.Sprintf("BackendUpdateActivity ActivityType error: %+v", in))
		logx.Errorw("BackendUpdateActivity ActivityType error")
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	if in.MutexType != nil {
		data.MutexType = uint8(*in.MutexType)
	}
	if in.ScopeType != nil {
		data.ScopeType = uint8(*in.ScopeType)
	}
	if in.TimesLimit != nil {
		data.TimesLimit = uint8(*in.TimesLimit)
	}

	if in.Name != nil {
		data.Name = strings.TrimSpace(*in.Name)

		filterMap := make(map[string]map[string][]any)
		filterMap[model.PromotionActivityColumns.Name] = map[string][]any{
			"equalTo": {data.Name},
		}
		filterMap[model.PromotionActivityColumns.Status] = map[string][]any{
			"notIn": {globalkey.StatusDeleted, globalkey.StatusFinished, globalkey.StatusInvalid},
		}
		list, _, err := l.svcCtx.Activity.GetList(l.ctx, model.M{
			"pageSize": uint64(2),
			"select":   ",",
		}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		count := len(list)
		if count > 1 {
			return nil, errorx.NewAlreadyExistsError("promotion.activityAlreadyExists")
		}

		if count == 1 && list[0].ID != id {
			return nil, errorx.NewAlreadyExistsError("promotion.activityAlreadyExists")
		}
	}
	if in.Slug != nil {
		data.Slug = strings.TrimSpace(*in.Slug)
	}
	if !skipContent {
		if in.Desc != nil {
			data.Description = *in.Desc
		}
		if in.FilteredDesc != nil {
			data.DescriptionFiltered = *in.FilteredDesc
		}
	}
	if in.MemberRestriction != nil && len(*in.MemberRestriction) > 0 {
		members := strings.Split(*in.MemberRestriction, ",")
		var newMembers []string
		for _, member := range members {
			newMember := strings.TrimSpace(member)
			if len(newMember) > 0 {
				newMembers = append(newMembers, strings.ToLower(newMember))
			}
		}
		if len(newMembers) > 0 {
			data.MemberRestriction = strings.Join(newMembers, ",")
		}
	}
	if in.StartedAt != nil {
		if localTime, err := modelx.ParseLocalTime(*in.StartedAt); err == nil {
			data.StartedAt = null.TimeFrom(localTime)
		}
	}
	if in.EndedAt != nil {
		if localTime, err := modelx.ParseLocalTime(*in.EndedAt); err == nil {
			data.EndedAt = null.TimeFrom(localTime.Add(time.Minute * -1))
		}
	}
	if in.Sort != nil {
		data.Sort = uint16(*in.Sort)
	}
	if in.Status != nil {
		data.Status = uint16(*in.Status)
	} else {
		data.Status = uint16(globalkey.StatusPending)
	}
	data.UpdatedAt = time.Now()

	rel := &model.PromotionActivityRel{}
	if skipContent {
		rel.Blacklist = append(rel.Blacklist, model.PromotionActivityColumns.Description)
		rel.Blacklist = append(rel.Blacklist, model.PromotionActivityColumns.DescriptionFiltered)
	}

	var thumbnailIdMetaId uint64
	var thumbnailUrlMetaId uint64
	if !skipMeta {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.PromotionActivityMetumColumns.ActivityID] = map[string][]any{
			"equalTo": {id},
		}
		list, _, err := l.svcCtx.Activity.GetMeta(l.ctx, model.M{}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if len(list) > 0 { // 原有的 Meta（决定现有的是增还是改）
			var omids []uint64
			oMetaMap := make(map[uint64]*model.PromotionActivityMetum)
			for _, v := range list {
				switch v.MetaKey { // 先排除特殊Key
				case "_thumbnail_id":
					thumbnailIdMetaId = v.MetaID
				case "_thumbnail_url":
					thumbnailUrlMetaId = v.MetaID
				default:
					omids = append(omids, v.MetaID)
					oMetaMap[v.MetaID] = v
				}
			}

			// 现有的 Meta（决定原有的是删还是留）
			nmidMap := make(map[uint64]struct{})
			if len(in.Meta) > 0 {
				for _, v := range in.Meta {
					if v.Key == nil || len(strings.TrimSpace(*v.Key)) == 0 {
						continue
					}

					if v.Value == nil || len(strings.TrimSpace(*v.Value)) == 0 {
						continue
					}

					var metum model.PromotionActivityMetum
					metum.ActivityID = id
					metum.MetaKey = strings.TrimSpace(*v.Key)
					metum.MetaValue = null.StringFrom(strings.TrimSpace(*v.Value))

					if v.Id != nil && *v.Id > 0 {
						if m, ok := oMetaMap[*v.Id]; ok { // 有值且是有效值，为修改，否则为新增
							nmidMap[*v.Id] = struct{}{} // 从删除中排除

							if m.MetaValue.Valid && m.MetaKey == metum.MetaKey && m.MetaValue.String == metum.MetaValue.String { // 不变，跳过
								continue
							}

							metum.MetaID = *v.Id
						}
					}

					rel.Meta = append(rel.Meta, &metum)
				}
			}

			for _, mid := range omids {
				if _, ok := nmidMap[mid]; !ok { // 当前不存在的值，应该删除
					rel.DelMetaIds = append(rel.DelMetaIds, mid)
				}
			}
		} else if len(in.Meta) > 0 { // 不存在原值，则都是新增
			for _, v := range in.Meta {
				if v.Key == nil || len(strings.TrimSpace(*v.Key)) == 0 {
					continue
				}

				if v.Value == nil || len(strings.TrimSpace(*v.Value)) == 0 {
					continue
				}

				var metum model.PromotionActivityMetum
				metum.ActivityID = id
				metum.MetaKey = strings.TrimSpace(*v.Key)
				metum.MetaValue = null.StringFrom(strings.TrimSpace(*v.Value))

				rel.Meta = append(rel.Meta, &metum)
			}
		}
	}

	if !skipMedia {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.PromotionAttachmentRelationshipColumns.ObjectID] = map[string][]any{
			"equalTo": {id},
		}
		filterMap[model.PromotionAttachmentRelationshipColumns.ObjectType] = map[string][]any{
			"equalTo": {globalkey.AttachmentLogTypePromotion},
		}
		list, _, err := l.svcCtx.Activity.GetMedia(l.ctx, model.M{}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		mediaUidMap := make(map[uint64]*model.PromotionAttachmentRelationship)
		if len(list) > 0 {
			for _, v := range list {
				mediaUidMap[v.AttachmentRelationshipID] = v
			}
		}

		allMediaMap := make(map[string]string)
		exclusiveMap := make(map[string]string) // 防删除原有图文中的图片
		if len(in.AllMedia) > 0 {
			for _, v := range in.AllMedia {
				if v.Id != nil && v.Url != nil && len(*v.Id) > 0 && len(*v.Url) > 0 {
					allMediaMap[*v.Id] = *v.Url
					exclusiveMap[*v.Url] = *v.Id
				}
			}
		}

		if len(in.NewMedia) > 0 {
			var thumbnailOrder uint
			var thumbnailId uint64
			var thumbnailUrl string
			for idx, v := range in.NewMedia {
				var url string
				if v.Url != nil && len(*v.Url) > 0 { // v.Uri  content版本（包含?id）  v.Url  url当前版本 | attachment当前版本
					url = *v.Url
				}
				var uri string
				if v.Uri != nil && len(*v.Uri) > 0 {
					uri = *v.Uri
					if len(url) == 0 {
						url = uri
					}
				}
				if len(url) == 0 {
					continue
				}

				var thumbnail uint8
				if v.Thumbnail != nil && *v.Thumbnail > 0 {
					thumbnail = uint8(*v.Thumbnail)
				}
				var order uint
				if v.Order != nil {
					order = uint(*v.Order)
				} else {
					order = uint(idx) + globalkey.AttachmentOrderOffset
				}
				var altText string
				if v.AltText != nil && len(*v.AltText) > 0 {
					altText = *v.AltText
				}
				var meta []string
				if v.Name != nil && len(*v.Name) > 0 {
					meta = append(meta, "filename:"+*v.Name)
					if len(altText) == 0 {
						altText = *v.Name
					}
				}
				if v.MetaData != nil && len(*v.MetaData) > 0 {
					meta = append(meta, *v.MetaData)
				}
				if v.MimeType != nil && len(*v.MimeType) > 0 {
					meta = append(meta, "mimeType:"+*v.MimeType)
				}
				metaData := strings.Join(meta, ";")

				var mediaId uint64
				if v.Id != nil && len(*v.Id) > 0 {
					if i, err := strconv.ParseInt(*v.Id, 10, 64); err == nil {
						mediaId = uint64(i)
					}
				}
				var uid uint64
				if v.Uid != nil && *v.Uid > 0 {
					uid = *v.Uid
				}

				if uid > 0 { // 原有缩略图
					if _, ok := mediaUidMap[uid]; ok { // 存在，修改，否则无效
						delete(mediaUidMap, uid)
						rel.Media = append(rel.Media, &model.PromotionAttachmentRelationship{
							AttachmentRelationshipID: uid,
							AttachmentID:             mediaId,
							AttachmentThumbnail:      thumbnail,
							AttachmentOrder:          order,
							AttachmentImageURL:       url,
							AttachmentImageAlt:       altText,
							AttachmentImageMeta:      metaData,
						})
					}
					continue
				}

				media := &model.PromotionAttachmentRelationship{
					AttachmentID:        mediaId,
					AttachmentThumbnail: thumbnail,
					AttachmentOrder:     order,
					AttachmentImageURL:  url,
					AttachmentImageAlt:  altText,
					AttachmentImageMeta: metaData,
				}

				if thumbnail == 0 && mediaId > 0 { // thumbnail == 0 不是缩略图， mediaId > 0 不是外链，获取图文uri
					if uri, ok := allMediaMap[*v.Id]; ok {
						media.AttachmentSource = uri
					}
				}

				rel.Media = append(rel.Media, media)
			}

			for _, v := range rel.Media {
				if v.AttachmentThumbnail > 0 && (len(thumbnailUrl) == 0 || thumbnailOrder > v.AttachmentOrder) { // thumbnailOrder尚未赋值，或当前值更小
					thumbnailOrder = v.AttachmentOrder
					thumbnailId = v.AttachmentID
					thumbnailUrl = v.AttachmentImageURL
				}
			}

			if len(thumbnailUrl) > 0 {
				rel.Meta = append(rel.Meta, &model.PromotionActivityMetum{
					MetaID:    thumbnailIdMetaId,
					MetaKey:   "_thumbnail_id",
					MetaValue: null.StringFrom(strconv.FormatInt(int64(thumbnailId), 10)),
				})
				rel.Meta = append(rel.Meta, &model.PromotionActivityMetum{
					MetaID:    thumbnailUrlMetaId,
					MetaKey:   "_thumbnail_url",
					MetaValue: null.StringFrom(thumbnailUrl),
				})
			}
		}

		for _, v := range mediaUidMap {
			if _, ok := exclusiveMap[v.AttachmentSource]; ok { // 如果在图文中，保留一次
				delete(exclusiveMap, v.AttachmentSource)
				continue
			}

			rel.DelMediaIds = append(rel.DelMediaIds, v.AttachmentRelationshipID)
		}
	}

	switch data.ActivityType {
	case enum.PromotionActivityDiscount, enum.PromotionActivityMember, enum.PromotionActivityCharge:
		if in.ScopeType != nil {
			data.ScopeType = uint8(*in.ScopeType)
		}
		if in.GroupMode != nil {
			data.GroupMode = uint8(*in.GroupMode)
		}
		if in.GroupType != nil {
			data.GroupType = uint8(*in.GroupType)
		}
		if len(in.Groups) > 0 {
			groupRelFilterMap := make(map[string]map[string][]any)
			groupRelFilterMap[model.PromotionRuleGroupColumns.ActivityID] = map[string][]any{
				"equalTo": {id},
			}
			groupRel, _, err := l.svcCtx.Activity.GetRuleGroupList(l.ctx, model.M{}, -1, groupRelFilterMap)
			if err != nil {
				return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			}

			ruleRelFilterMap := make(map[string]map[string][]any)
			ruleRelFilterMap[model.PromotionRuleColumns.ActivityID] = map[string][]any{
				"equalTo": {id},
			}
			ruleRel, _, err := l.svcCtx.Activity.GetRuleList(l.ctx, model.M{}, -1, ruleRelFilterMap)
			if err != nil {
				return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			}

			groups, delGroupIds, err := l.ParseDiscountRuleGroup(data.GroupMode, in.Groups, groupRel, ruleRel)
			if err != nil {
				return nil, err
			}

			rel.Groups = groups
			rel.DelGroupIds = delGroupIds
		}
	case enum.PromotionActivitySeckill:
		if in.SeckillLimit != nil {
			data.SeckillLimit = uint8(*in.SeckillLimit)
		}
		if in.SeckillCancelDuration != nil {
			data.SeckillCancelDuration = uint8(*in.SeckillCancelDuration)
		}
		if in.SeckillNotifyDuration != nil {
			data.SeckillNotifyDuration = uint8(*in.SeckillNotifyDuration)
		}
	case enum.PromotionActivityPackage:
		if in.PackageType != nil {
			data.PackageType = uint8(*in.PackageType)
		}
		if in.PackagePicId != nil {
			data.PackagePicID = *in.PackagePicId
		}
		if in.PackagePicUrl != nil {
			data.PackagePicURL = strings.TrimSpace(*in.PackagePicUrl)
		}
	default:
		// logrus.Info(fmt.Sprintf("BackendUpdateActivity ActivityType case error: %+v", in))
		logx.Errorw("BackendUpdateActivity ActivityType case error")
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	err = l.svcCtx.Activity.Update(l.ctx, tx, data, rel)
	if err != nil {
		tx.Rollback()
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	tx.Commit()

	return &promotion.BaseResp{
		Msg: i18n.UpdateSuccess,
	}, nil
}

func (l *BackendUpdateActivityLogic) ParseDiscountRuleGroup(
	mode uint8,
	groups []*promotion.ActivityRuleGroupInfo,
	groupRel []*model.PromotionRuleGroup,
	ruleRel []*model.PromotionRule,
) (groupRels []*model.PromotionRuleGroupRel, delGroupIds []uint64, err error) {
	var gids []uint64
	ogidMap := make(map[uint64]struct{})
	if len(groupRel) > 0 { // 原有的 RuleGroups（决定现有的是增还是改）
		for _, v := range groupRel {
			gids = append(gids, v.GroupID)
			ogidMap[v.GroupID] = struct{}{}
		}
	}

	// 现有的 RuleGroups（决定原有的是删还是留）
	ngidMap := make(map[uint64]struct{})
	for idx, v := range groups {
		var group model.PromotionRuleGroup
		if v.Threshold != nil {
			switch mode {
			case enum.PromotionActivityRuleGroupAmount:
				if i, err := moneyx.ParseAmount(*v.Threshold); err == nil && i > 0 {
					group.Threshhold = uint64(i)
				} else {
					logrus.Info(fmt.Sprintf("BackendUpdateActivity Threshold error 1: %+v", v.Threshold))
					return nil, nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
				}
			case enum.PromotionActivityRuleGroupNumber:
				if i, err := strconv.ParseInt(*v.Threshold, 10, 32); err == nil && i > 0 {
					group.Threshhold = uint64(i)
				} else {
					logrus.Info(fmt.Sprintf("BackendUpdateActivity Threshold error 2: %+v", v.Threshold))
					return nil, nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
				}
			default:
				logrus.Info(fmt.Sprintf("BackendUpdateActivity Threshold error 3: %+v", v.Threshold))
				return nil, nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
			}
		}

		if v.Sort != nil {
			group.Sort = uint16(*v.Sort)
		} else {
			group.Sort = uint16(idx + 1)
		}
		if v.Status != nil {
			group.Status = uint8(*v.Status)
		} else {
			group.Status = uint8(globalkey.StatusEnabled)
		}

		rules, delRuleIds, err := l.ParseDiscountRule(v.Rules, ruleRel)
		if err != nil {
			return nil, nil, err
		}

		if v.Id != nil && *v.Id > 0 {
			if _, ok := ogidMap[*v.Id]; ok { // 有值且是有效值
				ngidMap[*v.Id] = struct{}{}
				group.GroupID = *v.Id
			}
		}

		groupRels = append(groupRels, &model.PromotionRuleGroupRel{
			Group:      &group,
			Rules:      rules,
			DelRuleIds: delRuleIds,
		})
	}

	for _, gid := range gids {
		if _, ok := ngidMap[gid]; !ok { // 当前不存在的值
			delGroupIds = append(delGroupIds, gid)
		}
	}

	return
}

func (l *BackendUpdateActivityLogic) ParseDiscountRule(
	rules []*promotion.ActivityRuleInfo,
	ruleRel []*model.PromotionRule,
) (list []*model.PromotionRule, delRuleIds []uint64, err error) {
	var rids []uint64
	oridMap := make(map[uint64]struct{})
	if len(ruleRel) > 0 { // 原有的 Rules（决定现有的是增还是改）
		for _, v := range ruleRel {
			rids = append(rids, v.RuleID)
			oridMap[v.RuleID] = struct{}{}
		}
	}

	// 现有的 Rules（决定原有的是删还是留）
	nridMap := make(map[uint64]struct{})
	if len(rules) > 0 {
		for idx, v := range rules {
			var rule model.PromotionRule

			if v.RuleType != nil {
				rule.RuleType = uint8(*v.RuleType)

				switch rule.RuleType {
				case enum.PromotionActivityRuleTypeDiscount:
					if v.Mode != nil {
						rule.Mode = uint8(*v.Mode)

						if v.Value != nil {
							switch rule.Mode {
							case enum.PromotionActivityRuleModeAmount:
								if i, err := moneyx.ParseAmount(*v.Value); err == nil {
									rule.Value = uint64(i)
								} else {
									logrus.Info(fmt.Sprintf("BackendUpdateActivity rule.Mode error 1: %+v", rule.Mode))
									return nil, nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
								}
							case enum.PromotionActivityRuleModeDiscount:
								if i, err := strconv.ParseInt(*v.Value, 10, 32); err == nil && i > 0 && i <= 100 {
									rule.Value = uint64(i)
								} else {
									logrus.Info(fmt.Sprintf("BackendUpdateActivity rule.Mode error 2: %+v", rule.Mode))
									return nil, nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
								}
							case enum.PromotionActivityRuleModeFixed:
								if i, err := moneyx.ParseAmount(*v.Value); err == nil {
									rule.Value = uint64(i)
								} else {
									logrus.Info(fmt.Sprintf("BackendUpdateActivity rule.Mode error 3: %+v", rule.Mode))
									return nil, nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
								}
							default:
								logrus.Info(fmt.Sprintf("BackendUpdateActivity rule.Mode error 4: %+v", rule.Mode))
								return nil, nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
							}
						}
					}
				case enum.PromotionActivityRuleTypeFreeShipping:
					if v.Mode != nil {
						rule.Mode = uint8(*v.Mode)
					}

					if v.Regions != nil {
						rule.Regions = null.JSONFrom([]byte(strings.TrimSpace(*v.Regions)))
					}
				case enum.PromotionActivityRuleTypeExtraPoint:
					if v.Value != nil {
						if i, err := strconv.ParseInt(*v.Value, 10, 32); err == nil && i > 0 {
							rule.Value = uint64(i)
						} else {
							logrus.Info(fmt.Sprintf("BackendUpdateActivity rule.RuleType error 3: %+v", rule.RuleType))
							return nil, nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
						}
					}
				case enum.PromotionActivityRuleTypeCoupon:
					if v.Value != nil {
						if i, err := strconv.ParseInt(*v.Value, 10, 32); err == nil && i > 0 {
							rule.Value = uint64(i)
						} else {
							// logrus.Info(fmt.Sprintf("BackendUpdateActivity rule.RuleType error 4: %+v", rule.RuleType))
							// return nil, nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
						}
					}
				default:
					logrus.Info(fmt.Sprintf("BackendUpdateActivity rule.RuleType error 5: %+v", rule.RuleType))
					return nil, nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
				}
			}
			if v.Sort != nil {
				rule.Sort = uint16(*v.Sort)
			} else {
				rule.Sort = uint16(idx + 1)
			}
			if v.Status != nil {
				rule.Status = uint8(*v.Status)
			} else {
				rule.Status = uint8(globalkey.StatusEnabled)
			}

			if v.Id != nil && *v.Id > 0 {
				if _, ok := oridMap[*v.Id]; ok { // 有值且是有效值
					nridMap[*v.Id] = struct{}{}
					rule.RuleID = *v.Id
				}
			}

			list = append(list, &rule)
		}
	}

	for _, rid := range rids {
		if _, ok := nridMap[rid]; !ok { // 当前不存在的值
			delRuleIds = append(delRuleIds, rid)
		}
	}

	return
}
